# 简化人脸识别
import face_recognition
import cv2
import requests
from train import known_names
from train import known_encodings

taskId = 2

# 用于记录已经识别过的人脸
recognized_faces = set()

# 定义服务器的地址
url = 'http://localhost:8080/camera/processFaceRecogData'  # 根据实际情况修改

# 打开摄像头
video_capture = cv2.VideoCapture(0)

while True:
    # 读取摄像头画面
    ret, frame = video_capture.read()

    # 将摄像头画面转换为 RGB格式
    rgb_frame = frame[:, :, ::-1]

    # 在画面中检测人脸
    face_locations = face_recognition.face_locations(rgb_frame)
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    for face_encoding in face_encodings:
        # 与已知人脸进行对比
        matches = face_recognition.compare_faces(known_encodings, face_encoding, tolerance=0.5)
        name = "Unknown"

        if True in matches:
            # 找到匹配的人脸
            matched_index = matches.index(True)
            name = known_names[matched_index]

            # 如果之前没有识别过该人脸，则发送请求给服务器
            if name not in recognized_faces:
                recognized_faces.add(name)

                # 发送POST请求给服务器
                data = {
                    'studentId': name,
                    'taskId': taskId # 这里可以根据实际情况设定置信度
                }
                print(data)
                print("发送请求 ")
                headers = {'Content-Type': 'application/json'}
                response = requests.post(url, json=data, headers=headers)
                # print(response.status_code)
                if response.status_code == 200:
                    print("请求成功")
                else:
                    print("请求失败")
                print(response.text)

        # 在画面中标出人脸和名称
        top, right, bottom, left = face_locations[0]
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        cv2.putText(frame, name, (left, bottom + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

    # 显示识别结果
    cv2.imshow('Face Recognition', frame)

    # 按下 'q' 键退出程序
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头资源
video_capture.release()
cv2.destroyAllWindows()